package com.hh.vietnameseproject.ui.person

import android.app.Dialog
import android.content.Context
import android.view.Gravity
import android.view.ViewGroup
import android.widget.Toast
import com.hh.vietnameseproject.R
import com.hh.vietnameseproject.databinding.AddPasswordDialogBinding
import com.hh.vietnameseproject.databinding.ChangeNameDialogBinding
import com.hh.vietnameseproject.logic.network.AllNetWork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject

class ChangeNameDialog: Dialog {
    constructor(context: Context) : this(context,0)
    constructor(context: Context, themeResId: Int) : super(context,R.style.dialog){
        val binding = ChangeNameDialogBinding.inflate(layoutInflater)
        setContentView(binding.root)
        window?.setGravity(Gravity.CENTER)
        window?.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        setCancelable(true)
        binding.changeNameClose.setOnClickListener {
            dismiss()
        }
        binding.changeNameBtn.setOnClickListener {
            val name = binding.changeNameEt.text.toString().trim()
            GlobalScope.launch {
                val body = AllNetWork.changeName(name)
                val jsonObject = JSONObject(body.string())
                withContext(Dispatchers.Main) {
                    if (jsonObject.getInt("code")==1){
                        (context as PersonActivity).changeName(name)
                    }
                    Toast.makeText(context,"${jsonObject.getString("message")}",Toast.LENGTH_SHORT).show()
                    dismiss()
                }
            }
        }
    }

}